//
//  AsyncConnection.m
//  3.异步2
//
//  Created by 霍文轩 on 15/8/12.
//  Copyright (c) 2015年 霍文轩. All rights reserved.
//

#import "AsyncGETConnection.h"

@interface AsyncGETConnection ()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
@end

@implementation AsyncGETConnection
-(void)dealloc{
    Block_release(self.finishBlock);
    [_receiveData release];
    [super dealloc];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.receiveData = [NSMutableData data];
    }
    return self;
}



+ (instancetype)asyncConnectionWithURLString:(NSString *)urlString parmaters:(NSDictionary *)parmaters block:(void (^)(NSData *))block{
    AsyncGETConnection * async = [[AsyncGETConnection alloc] init];
    
    async.finishBlock = block;
    
    NSArray * objArr = [parmaters allValues];
    NSArray * keyArr = [parmaters allKeys];
    for(int i=0;i<[parmaters count];i++){
        if(i == 0)
            urlString = [NSString stringWithFormat:@"%@?",urlString];

        urlString = [urlString stringByAppendingString:[NSString stringWithFormat:@"%@=%@",[keyArr objectAtIndex:i],[objArr objectAtIndex:i]]];
        
        if(i!=[parmaters count]-1)
            urlString = [urlString stringByAppendingString:@"&"];
    }
    
    NSLog(@"%@",urlString);

    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [async startConnectionWithURLString:urlString];
    return [async autorelease];
}
-(void)startConnectionWithURLString:(NSString *)urlString{
    NSURL * url = [NSURL URLWithString:urlString];
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection connectionWithRequest:request delegate:self];
    [request release];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_receiveData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    self.finishBlock(self.receiveData);
}
@end
